import Footer from '@/components/Footer';
import WeChatDrawer from '@/components/WeChatDrawer';
import { loginAppForPhone, loginAppForWechatAuthorize } from '@/services/api/api-login';
import { setToken } from '@/utils/token';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-form';
import { Alert, Spin, Tabs, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { Helmet, history, useModel } from 'umi';

type LoginParams = {
  phone?: string;
  password?: string;
  autoLogin?: boolean;
  type?: string;
};

const Login: React.FC = () => {
  const [type, setType] = useState<string>('wechat');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [weChatUrl, setWeChatUrlState] = useState<string>();
  const isDev = process.env.NODE_ENV === 'development';
  // const isDev = true;
  useEffect(() => {
    loginAppForWechatAuthorize({ serviceName: 'cqgxq' }).then(({ code, data }) => {
      if (code === 0) {
        setWeChatUrlState(data);
      }
    });
  }, []);

  const handleSubmit = async (values: LoginParams) => {
    // 登录
    const response = await loginAppForPhone({ ...values, type, serviceName: 'cqgxq' });
    if (response.code === 0) {
      setToken(response.data.satoken);
      /** 此方法会跳转到 redirect 参数所在的位置 */
      if (!history) return;
      // const { query } = history.location;
      // const { redirect } = query as { redirect: string };
      // history.push(redirect || '/');
      const userInfo = await initialState?.fetchUserInfo?.();
      if (userInfo) {
        message.success('登录成功！');
        history.push('/');
        flushSync(() => {
          setInitialState((s) => ({
            ...s,
            currentUser: userInfo,
          }));
        });
      }

      return;
    }
  };

  const titleC = () => {
    return <></>;
  };

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        overflow: 'auto',
        backgroundImage:
          "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
        // backgroundImage: '/page_login_layout_bg_img_4.png',
        backgroundSize: '100% 100%',
      }}
    >
      <Helmet>
        <title>登录页 - 融媒通</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <div
          style={{
            alignContent: 'center',
            display: 'flex',
            justifyContent: 'center',
            marginBottom: '-10px',
          }}
        >
          <img alt="logo" width={256} src="/logo2.png" />
        </div>
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
            marginTop: '-10px',
          }}
          // title={<span style={{ color: '#5E5C5D' }}>融媒通</span>}
          subTitle={false}
          // initialValues={{
          //   autoLogin: true,
          // }}
          submitter={
            type === 'phone' && {
              searchConfig: {
                submitText: '登录',
              },
              submitButtonProps: {
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }
          }
          onFinish={async (values) => {
            await handleSubmit(values as LoginParams);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'wechat',
                label: '微信登录',
              },
              {
                key: 'wxamp',
                label: '微信小程序',
              },
              isDev && {
                key: 'phone',
                label: '手机号密码登录',
              },
            ]}
          />
          {type === 'wechat' && (
            <div style={{ paddingTop: 20, overflow: 'auto', textAlign: 'center', minHeight: '400px' }}>
              <Spin spinning={!weChatUrl}>
                <iframe src={weChatUrl} height="404" frameBorder="0" scrolling="false" />
              </Spin>
              {/* {weChatUrl ? <iframe src={weChatUrl} height="404" frameBorder="0" scrolling="false" /> : <Spin />} */}
            </div>
          )}
          {type === 'wxamp' && (
            <div style={{ paddingTop: 20, overflow: 'auto', textAlign: 'center' }}>
              <img
                src="/wxamp-qrcode.png"
                style={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                }}
              />
            </div>
          )}
          {isDev && type === 'phone' && (
            <div>
              <ProFormText
                name="phone"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'手机号'}
                rules={[
                  {
                    required: true,
                    message: '请输入手机号',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
            </div>
          )}

          <Alert
            style={{
              marginTop: '25px',
            }}
            message={
              <>
                注意，请使用Chrome或Edge浏览器，不推荐使用微信内置浏览器
                <WeChatDrawer />
              </>
            }
            type="warning"
          />
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
